// pages/care/index/index.js
import { GetElderlyByEmployeeId } from '../../../apis/modules/elderly'
import { WeChatZhaohuAppletLogin } from '../../../apis/modules/wechat';
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loginIng:true,
    userIsLogin:false,
    isNeedRefresh:false,
    elderlys:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({userIsLogin:app.globalData.userIsLogin});
  },

  // 加载我照护的老人列表
  LoadElderlyByEmployeeId:function(){
    var userEmployeeId = app.globalData.userEmployeeId;
    if(userEmployeeId>0){
        GetElderlyByEmployeeId(userEmployeeId).then(res=>{
            this.setData({elderlys:res.data,isNeedRefresh:false})
        })
    }
  },
  clickMissionItemEvent:function(e){
    var mission=e.currentTarget.dataset.mission;
    var elderly=e.currentTarget.dataset.elderly;
    this.setData({isNeedRefresh:true});
    wx.navigateTo({
      url: `/pages/care/care-publish/care-publish?mId=${mission.id}&elderlyId=${elderly.id}&elderlyName=${elderly.name}`,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({userIsLogin:app.globalData.userIsLogin});
    if(this.data.userIsLogin){
        this.LoadElderlyByEmployeeId();
    }else{
        const that=this;
        this.setData({loginIng:true});
        wx.login({
            success (res) {
              if (res.code) {
                WeChatZhaohuAppletLogin({js_code:res.code}).then((res) => {
                    if(res.data.userToken == null && res.data.userSessionInfo.openId!=''){
                        that.setData({loginIng:false});
                    }else{
                        app.globalData.userInfo = res.data.userInfo;
                        app.globalData.userToken =res.data.userToken;
                        app.globalData.userSessionInfo=res.data.userSessionInfo;
                        app.globalData.userIsLogin = true;
                        app.globalData.userEmployeeId=res.data.userInfo.employeeId;
                        app.globalData.userCompanyId=res.data.userInfo.companyId;
                        var loginInfo= JSON.stringify(res.data);
                        wx.setStorage({key:"login-info",data:loginInfo});
                        that.setData({userIsLogin:true,loginIng:false});
                        that.LoadElderlyByEmployeeId();
                    }
                })
              } 
            }
          })
    }
  },
  clickGoLoginEvent:function(){
    wx.clearStorageSync();
    wx.redirectTo({
        url: '/pages/login/login-index/login-index?autoLogin=false'
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})